package com.nakamachizu.controller.m;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.StringUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.nakamachizu.model.MapData;
import com.nakamachizu.model.MarkData;
import com.nakamachizu.util.ErrorsUtil;
import com.nakamachizu.util.ForwardUtil;

public class EditorController extends Controller {

    private static final Logger log = Logger.getLogger(EditorController.class.getName());
    private String keyStr;
    private String cmd_mod;
    private String cmd_del;
    private String name;
    private String comment;
    protected List<String> messages = new ArrayList<String>();
    
    @Override
    public Navigation run() {
        UserService userService = UserServiceFactory.getUserService();        
        User user = userService.getCurrentUser();
        String logoutUrl = userService.createLogoutURL("/");
        
        if(user == null){
            return redirect(userService.createLoginURL(request.getRequestURI()));
        }
        
        this.init();
        
        if(validate()){
            Key key = KeyFactory.stringToKey(keyStr);
            MarkData mark = Datastore.get(MarkData.class, key);
            MapData map = mark.getMapDataRef().getModel();
            
            if(mark == null || !map.getAdminMailAddress().equals(user.getEmail())){
                return redirect("/");
            }
            // 編集
            if(!StringUtil.isEmpty(cmd_mod)){
                boolean modify = false;
                if(name == null){
                    name = "";
                }
                if(comment == null){
                    comment = "";
                }
                if(!name.equals(mark.getName())){
                    mark.setName(name);
                    modify = true;
                }
                if(!comment.equals(mark.getComment())){
                    mark.setComment(comment);
                    modify = true;
                }
                
                if(modify){
                    Datastore.put(mark);
                    return redirect("/view");
                }
                
            // 削除
            }else if(!StringUtil.isEmpty(cmd_del)){
                Datastore.delete(key);
                return redirect("/view");
            }
            
            requestScope("name", mark.getName());
            requestScope("comment", mark.getComment());

        }
        
        return forward(ForwardUtil.forwardJsp("edit.jsp"));
    }
    
    @Override
    protected Navigation handleError(Throwable error) {
        error.printStackTrace();
        log.severe(ErrorsUtil.stackTrace(error));
        return forward("/error.jsp");
    }
    
    protected boolean validate() {
        boolean result = false;
        Validators v = new Validators(request);
        v.add("key", v.required());
        if(!StringUtil.isEmpty(cmd_mod) || !StringUtil.isEmpty(cmd_mod)){
            v.add("name", v.required());
            v.add("comment", v.required());
        }
        result = v.validate();
        
        return result;
    }
    
    protected void init(){
        keyStr = requestScope("key");
        cmd_mod = requestScope("cmd_mod");
        cmd_del = requestScope("cmd_del");
        name = requestScope("name");
        comment = requestScope("comment");
    }
}
